<template>
  <div class="clearfix">
    <a-upload
      :showUploadList="showUploadList"
      :disabled="loading"
      list-type="picture-card"
      accept=".jpg,.jpeg,.png,.JPG,.JPEG"
      :file-list="fileList"
      @preview="handlePreview"
      :remove="remove"
      :beforeUpload="handleUpload">
      <div v-if="fileList.length < maxLength">
        <a-icon :type="loading ? 'loading' : 'plus'" />
        <div class="ant-upload-text">
          上传
        </div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
  import {
    btnUpload,
    uuid,
    getTime,
    extname
  } from '@/utils/upload'
  import {
    btnReturnToken
  } from '@/api/upload'
  import { message } from 'ant-design-vue'
  function getBase64 (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }
  // import { UploadOutlined } from '@ant-design/icons-vue'
  export default {
    // props: ['maxLength', 'value', 'showUploadList'],
    props: {
      maxLength: {
        type: Number,
        default: 0
      },
      value: {
        type: String,
         default: ''
      },
      showUploadList: {
        type: Array,
         default: () => []
      }
    },
    data () {
      return {
        fileList: [],
        loading: false,
        previewVisible: false,
        previewImage: ''
      }
    },
    watch: {
      value (n) {
        if (typeof n === 'string') {
          this.fileList = [{
            name: new Date().getTime() + 'TYKJ',
            status: 'done',
            uid: 0,
            url: n
          }]
        } else {
          this.fileList = n || []
        }
      },
      fileList (value) {
        if (value.length > 0) this.$emit('change', value)
      }
    },
    methods: {
      setInitFileList (ev) {
        this.fileList = ev
        // this.fileList.push(ev[0])
        // this.$set(this.fileList, 0, ev)
      },
      remove (ev) {
        try {
          this.fileList.splice(ev.uid, 1)
        } catch (e) {}
      },
      handleCancel () {
        this.previewVisible = false
      },
      async handlePreview (file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      handleUpload (file) {
        // 校验文件
        if (file.size / 1024 / 1024 > 3) {
          const isRightSize = file.size / 1024 / 1024 < 3
          if (!isRightSize) {
            message.warning('文件大小超过 3MB')
          }
          return isRightSize
        } else {
          // 上传
          this.loading = true
          const hz = extname(file.name) // 后缀
          const sname = uuid(32, 32) // 随机名
          const from = {
            file_name: 'pc/goodsAdmin/addGoods/' + getTime() + '/' + sname + '.' + hz
          }
          btnReturnToken(from).then((res) => {
            const yname =
              'pc/goodsAdmin/addGoods/' + getTime() + '/' + sname + '.' + hz
            btnUpload(file, yname, res.upload_token)
              .then((res) => {
                message.success('上传成功')
                this.loading = false
                this.fileList.push({
                  uid: this.fileList.length,
                  name: file.name,
                  status: 'done',
                  url: res
                })
              })
              .catch((err) => {
                this.loading = false
                message.error(err)
              })
          })
        }
        return false
      }
    }
  }
</script>
<style>
  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>
